package qmlt.dataset;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import qmlt.dataset.utils.JSONUtils;

public class DataSetDef
{

	public String						id;

	public List<Attribute>	defs				= new ArrayList<Attribute>();

	public int							targetIndex;

	public List<Attribute>	featureDefs	= new ArrayList<Attribute>();

	public Attribute				targetDef;
	
	private DataSetDef()
	{
	}
	
	public DataSetDef(String id, List<Attribute> defs, int targetIndex)
	{
		this.id = id;
		this.defs = defs;
		this.targetIndex = targetIndex;
		
		for (int i = 0; i < defs.size(); ++i)
		{
			if (i != this.targetIndex)
			{
				featureDefs.add(defs.get(i));
			}
		}
		targetDef = defs.get(targetIndex);
	}
	
	public DataSetDef(String id, List<Attribute> featureDefs, Attribute targetDef)
	{
		this.id = id;
		this.defs = new ArrayList<Attribute>();
		defs.addAll(featureDefs);
		this.targetIndex = defs.size();
		this.featureDefs = featureDefs;
		this.targetDef = targetDef;
	}
	
	public DataSetDef clone(String newId)
	{
		DataSetDef newDef = new DataSetDef(newId, featureDefs, targetDef);
		return newDef;
	}

	public static DataSetDef read(String defFilepath) throws IOException, JSONException
	{
		BufferedReader br = new BufferedReader(new FileReader(defFilepath));
		StringBuilder sb = new StringBuilder();
		while (true)
		{
			String line = br.readLine();
			if (line == null)
				break;

			if (line.trim().isEmpty())
				continue;

			if (!line.startsWith("#"))
				sb.append(line);
		}
		br.close();

		JSONObject json = new JSONObject(sb.toString());

		DataSetDef def = new DataSetDef();
		def.id = json.getString("id");
		def.defs = JSONUtils.asAttributeList(json.getJSONArray("defs"));
		def.targetIndex = json.getInt("target-index");

		for (int i = 0; i < def.defs.size(); ++i)
		{
			if (i == def.targetIndex)
			{
				def.targetDef = def.defs.get(i);
			}
			else
			{
				def.featureDefs.add(def.defs.get(i));
			}
		}

		return def;
	}

}
